package io.gitee.xyuesheng.day05;

import org.junit.Assert;
import org.junit.Test;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class WordCount {
    @Test
    public void test() {
        String s1 = "Stack from overflow ";
        String s = "Stack Overflow requires external JavaScript from overflow " +
                "another or domain, which is blocked or failed to or load.";

        // 判断有几个不同的单词
        Assert.assertEquals(3, count(s1));
        Assert.assertEquals(16, count(s));

        // 判断每个单词的数量
        Map<String, Integer> map = countEach(s1);
        Assert.assertEquals(new Integer(1), map.get("stack"));
        // stack有1个

        map = countEach(s);
        Assert.assertEquals(new Integer(3), map.get("or"));
        // or有3个
        Assert.assertEquals(new Integer(2), map.get("overflow"));
        // overflow有2个
    }

    /**
     * 给定一个英文字符串，判断里面有几个不同的单词。（不区分大小写)
     *
     * @param s
     * @return
     */
    public int count(String s) {
        Set<String> set = new HashSet<>();

        // 使用,.和空格分隔字符串
        String[] array = s.split("[,. ]");

        for (String e : array) {
            set.add(e.toLowerCase());
        }

        return set.size();
    }

    /**
     * - 给定一个英文字符串，统计里面每个单词的个数。（不区分大小写)
     */

    public Map<String, Integer> countEach(String s) {
        Map<String, Integer> map = new HashMap<>();

        // 使用,.和空格分隔字符串
        String[] array = s.split("[,. ]");

        for (String e : array) {
            String key = e.toLowerCase();
            if (map.containsKey(key)) {   // map里面已经有某个单词的统计了
                int value = map.get(key);
                map.put(key, value + 1);
            } else {
                map.put(key, 1);
            }
        }
        return map;
    }
}
